import { inject, nextTick } from "vue";
import {
  CompDataItem,
  ConfigurationJSON,
  ConnectIds,
  DeviceJSON,
  FlowPathJSON,
  LabelValueJSON,
  PipePathJSON,
  SubId,
} from "/@/components/types";
import { ConfigurationEl, ConfigurationType, RootCommon, RootCommonKey } from "./types";
import { SvgDetail } from "/@/components/Device/resourceDetail";
import { cloneDeep } from "lodash-es";

export function useData() {
  const {
    deviceSvgData,
    deviceImageData,
    pipePathData,
    labelValueData,
    compInstance,
    connection,
    scaleFactor,
    flowPathData,
  } = inject(RootCommonKey) as RootCommon;

  function clearData() {
    deviceImageData.value = [];
    deviceSvgData.value = [];
    pipePathData.value = [];
    labelValueData.value = [];
    flowPathData.value = [];
    connection.clear();
    for (const key in compInstance) {
      delete compInstance[key];
    }
  }

  function exportData() {
    const data: CompDataItem[] = [];
    const all: ConfigurationEl[] = deviceSvgData.value
      .concat(deviceImageData.value)
      .concat(pipePathData.value)
      .concat(labelValueData.value)
      .concat(flowPathData.value);
    all.forEach((el) => {
      const ins = compInstance[el.id];
      if (ins) {
        data.push(ins.toJSON());
      }
    });
    const connData = connection.getData();
    const connectIds: ConnectIds = {};
    for (let id in connData) {
      if (
        id.startsWith(ConfigurationType.DeviceImage) ||
        id.startsWith(ConfigurationType.DeviceSvg) ||
        id.startsWith(ConfigurationType.FlowPath)
      ) {
        const subIds: SubId[] = [];
        connData[id].forEach((el) => {
          subIds.push({
            id: el.id,
            position: el.extra?.connectPositionIndex || 0,
          });
        });
        connectIds[id] = subIds;
      }
    }
    const json: ConfigurationJSON = {
      scaleFactor: scaleFactor.value,
      connectIds,
      compData: data,
    };
    console.log(JSON.stringify(json));
  }

  async function importData(data: ConfigurationJSON) {
    data = cloneDeep(data);
    scaleFactor.value = 1;
    clearData();
    await nextTick();
    const _deviceSvgData: ConfigurationEl[] = [];
    const _deviceImageData: ConfigurationEl[] = [];
    const _pipePathData: ConfigurationEl[] = [];
    const _labelValueData: ConfigurationEl[] = [];
    const _flowPathData: ConfigurationEl[] = [];
    const idJSON: { [key: string]: CompDataItem } = {};
    const compData = data.compData;
    compData.forEach((el) => {
      if (el.id.startsWith(ConfigurationType.DeviceImage) || el.id.startsWith(ConfigurationType.DeviceSvg)) {
        const deviceEl = el as DeviceJSON;
        const newEl: ConfigurationEl = {
          id: el.id,
          centerX: deviceEl.x + deviceEl.width / 2,
          centerY: deviceEl.y + deviceEl.width / 2,
          initWidth: deviceEl.width,
        };
        if (el.id.startsWith(ConfigurationType.DeviceImage)) {
          newEl.imgSrc = deviceEl.imgSrc;
          newEl.imgName = deviceEl.imgName;
          _deviceImageData.push(newEl);
        } else {
          newEl.componentName = deviceEl.componentName;
          newEl.centerY = deviceEl.y + deviceEl.width / SvgDetail[deviceEl.componentName as string].factor / 2;
          _deviceSvgData.push(newEl);
        }
      } else if (el.id.startsWith(ConfigurationType.LabelValue)) {
        const labelValueEl = el as LabelValueJSON;
        _labelValueData.push({
          id: labelValueEl.id,
          centerX: 0,
          centerY: 0,
        });
      } else if (el.id.startsWith(ConfigurationType.PipePath)) {
        const pipePathEl = el as PipePathJSON;
        _pipePathData.push({
          id: el.id,
          centerX: 0,
          centerY: 0,
          colors: pipePathEl.colors,
          pipePathType: pipePathEl.type,
        });
      } else if (el.id.startsWith(ConfigurationType.FlowPath)) {
        const flowPathEl = el as FlowPathJSON;
        _flowPathData.push({
          id: el.id,
          centerX: flowPathEl.x + flowPathEl.width / 2,
          centerY: flowPathEl.y + flowPathEl.height / 2,
          initWidth: flowPathEl.width,
          initHeight: flowPathEl.height,
          flowPathType: flowPathEl.type,
        });
      }
      idJSON[el.id] = el;
    });
    deviceImageData.value = _deviceImageData;
    deviceSvgData.value = _deviceSvgData;
    pipePathData.value = _pipePathData;
    labelValueData.value = _labelValueData;
    flowPathData.value = _flowPathData;
    await nextTick();
    const all: ConfigurationEl[] = deviceSvgData.value
      .concat(deviceImageData.value)
      .concat(pipePathData.value)
      .concat(labelValueData.value)
      .concat(flowPathData.value);
    all.forEach((el) => {
      const ins = compInstance[el.id];
      if (ins) {
        ins.setJSON(idJSON[el.id]);
      }
    });
    //还原连接关系
    const connectIds = data.connectIds;
    for (let deviceId in connectIds) {
      const subIds = connectIds[deviceId];
      const ins = compInstance[deviceId];
      if (ins && ins.getDragInfo) {
        const drag = ins.getDragInfo();
        subIds.forEach((subId) => {
          for (let i = 0; i < pipePathData.value.length; i++) {
            const pipePathIns = compInstance[pipePathData.value[i].id];
            if (pipePathIns && pipePathIns.setConnection) {
              const isSuccess = pipePathIns.setConnection(drag, subId);
              if (isSuccess) {
                break;
              }
            }
          }
        });
      }
    }
    scaleFactor.value = data.scaleFactor;
  }

  return {
    exportData,
    importData,
    clearData,
  };
}
